package com.cf.base.http;

import com.cf.base.http.annotation.Module;
import com.cf.base.http.core.RetrofitManager;
import com.cf.base.http.core.RetrofitService;
import com.cf.base.http.utils.TextUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author yangji
 */
public class HttpManager {

    public interface ServiceProvider {
        /**
         * @param moduleName 模块名称
         * @return 返回模块的service
         */
        RetrofitService getService(String moduleName);
    }


    private static HttpManager INSTANCE = null;

    private Map<String, ServiceProvider> serviceProviders;


    public static HttpManager getInstance() {
        if (INSTANCE == null) {
            synchronized (HttpManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new HttpManager();
                }
            }
        }
        return INSTANCE;
    }

    private HttpManager() {
        serviceProviders = new ConcurrentHashMap<>();
    }


    /**
     * 订阅模块
     *
     * @param moduleName 模块名称
     * @param provider   订阅构造器
     */
    public void registerProvider(String moduleName, ServiceProvider provider) {
        serviceProviders.put(moduleName, provider);
    }

    public synchronized <T> T create(Class<T> tClass) {
        Module http = tClass.getAnnotation(Module.class);
        if (http == null) {
            throw new NullPointerException(String.format("模块 %s 没有生命模块注解 ", tClass.getSimpleName()));
        }
        String moduleName = http.value();
        if (TextUtils.isEmpty(moduleName)) {
            throw new NullPointerException(String.format("模块 %s 模块注解 @Module 的 value 不能为空", tClass.getSimpleName()));
        }

        RetrofitService service = RetrofitManager.getInstance().getRetrofit(moduleName);

        if (service != null) {
            return service.create(tClass);
        }

        ServiceProvider provider = serviceProviders.get(moduleName);
        if (provider == null) {
            throw new NullPointerException(String.format("模块 %s 没有提供 ServiceProvider", moduleName));
        }

        service = provider.getService(moduleName);
        if (service == null) {
            throw new NullPointerException(String.format("模块%s 的 provider 提供了 null 的 Service", moduleName));
        }

        return provider.getService(moduleName).create(tClass);
    }

    /**
     * 如果中途切换了地址；则清空之前所有的 service 然后服务会通过构造器重新生成
     */
    public synchronized void clear() {
        RetrofitManager.getInstance().clear();
    }

    /**
     * 如果中途切换了地址； 然后服务会通过构造器重新生成
     */
    public synchronized void clear(String name) {
        RetrofitManager.getInstance().clear(name);
    }
}
